package com.itheima.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();

        System.out.println("LoginInterceptor拦截请求: " + uri);

        // 对登录相关请求和静态资源放行
        if(uri.contains("/login") || uri.contains("/tologin")
                || uri.contains("/js/") || uri.contains("/css/")
                || uri.contains("/images/") || uri.equals(contextPath + "/")
                || uri.contains("/fileupload.jsp") || uri.contains("/fileUpload")
                || uri.contains("/getFilesName") || uri.contains("/download")) {
            return true;
        }

        HttpSession session = request.getSession();
        // 如果用户已登录，放行
        if(session.getAttribute("USER_SESSION") != null) {
            return true;
        }

        // 其他情况跳转到登录页面
        request.setAttribute("msg", "您还没有登录，请先登录！");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                .forward(request, response);
        return false;
    }
}